from threading import activeCount

from django import forms
from django.core import validators
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from web import models
from django_redis import get_redis_connection
from utils.encrypt import md5

class LoginForm(forms.Form):

    role = forms.ChoiceField(
        label='Role',
        required=True,
        widget=forms.Select(attrs={'class': 'form-control'}),
        choices=[(1,"管理员"),(2,"用户")],
    )
    username = forms.CharField(
        label="用户名",
        required=True,
        max_length=20,
        widget=forms.TextInput(attrs={"placeholder":"用户名",'class': 'form-control'}),
        validators=[
            #1 用户名只能包含字母数字下划线
            lambda value: all(c.isalnum() or c == "_" for c in value),
            #2 禁止下划线开头或结尾
            lambda value: not value.startswith("_") and not value.endswith("_"),
        ],
        error_messages={
            'required':"用户名不能为空",
            'max_length':"用户名最长不超过20",
        },
    )

    def _validate_username_chars(value):
        if not all(c.isalnum() or c == "_" for c in value):
            raise ValidationError(
                "用户名只能包含字母数字下划线",
                code='invalid_chars', # 唯一错误码
            )

    def _validate_username_underscore(value):
        if value.startswith("_") and value.endswith("_"):
            raise ValidationError(
                "禁止下划线开头或结尾",
                code='invalid_underscore',  # 唯一错误码
            )

    password = forms.CharField(
        label="密码",
        required=True,
        widget=forms.PasswordInput(attrs={"placeholder":"密码",'class': 'form-control'}),
        error_messages={
            "required": "密码不能为空",
            "min_length": "密码至少8位",
            "max_length": "密码最多20位",
        }
    )

    def clean_password(self):
        password = self.cleaned_data['password']
        return md5(password)

class SmsCodeForm(forms.Form):
    role = forms.ChoiceField(
        label="角色",
        required=True,
        choices=(("2", "客户"), ("1", "管理员")),
        widget=forms.Select(attrs={"class": "form-control"})
    )
    mobile = forms.CharField(
        label='手机号',
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格式错误'),],
        error_messages={
            "required": "手机号不能为空",
        }
    )

    def clean_mobile(self):
        mobile = self.cleaned_data['mobile']
        role = self.cleaned_data['role']
        if role == '1':
            exists = models.Administrator.objects.filter(active=1,mobile=mobile).exists()
        else:
            exists = models.Customer.objects.filter(active=1,mobile=mobile).exists()
        if not exists:
            raise ValidationError("手机号不存在")
        return mobile


class SmsLoginForm(forms.Form):
    role = forms.ChoiceField(
        label='Role',
        required=True,
        widget=forms.Select(attrs={'class': 'form-control'}),
        choices=[(1, "管理员"), (2, "用户")],
    )
    mobile = forms.CharField(
        label='手机号',
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        # validators=[r'^1[3-9]\d{9}$'], 错误写法 报错TypeError: 'str' object is not callable
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')],  # 修正：使用 RegexValidator 创建验证器对象
        error_messages={
            "required": "手机号不能为空",
        }
    )
    code = forms.CharField(
        label="验证码",
        required=True,
        validators=[RegexValidator(r'^\d{6}$','验证码格式不正确'),],
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        error_messages={
            "required": "验证码不能为空",
        }
    )

    def clean_code(self):
        code = self.cleaned_data['code']
        conn = get_redis_connection('default')
        real_code = conn.get('mobile_code')
        if not real_code:
            raise ValidationError("验证码未发送或失效")
        if code != real_code.decode('utf-8'):
            raise ValidationError("验证码错误或失效")
        return code


